<?php
class ProjectIndexController  extends Zone_Action{
	protected function fields(){
		$data = array(
			date_updated		=> array(
				type			=> 'NONE',
				default_value	=> mysql_date()
			),		
			updated_by_id	=> array(
				type			=> 'NONE',
				default_value	=> get_user_id()
			),		
			code	=> array(
				type		=> 'CHAR',
				no_empty	=> true,
				form_label	=> 'Mã dự án'
			),		
			title => array(
				type 		=> 'CHAR',
				no_empty 	=> true,
				form_label 	=> 'Tiêu đề',
				default_value 	=> ''
			),
			desc => array(
				type 	   		=> 'HTML',
				form_label 		=> 'Mô tả',
				default_value 	=> ''
			),
			date_start	=>array(
				type		=> 'DATE',
				fix_value	=> change_date_format, 
				form_label 	=> 'Ngày bắt đầu',
				default_value	=> NULL
			),
			date_end_forecast => array(
				type			=> 'DATE',
				fix_value		=> change_date_format,
				form_label  	=> 'Ngày dự kiến kết thúc',
				default_value	=> NULL				
			),
			date_end	=> array(
				type		=> 'DATE',
				fix_value	=> change_date_format, 
				form_label  => 'Ngày kết thúc thực tế',
				default_value	=> NULL				
			),
			rate	=> array(
				type			=> 'INT',
				max				=> 100,
				min				=> 0,
				form_label  	=> 'Tiến độ',
				default_value	=>	0
			),
			status	=> array(
				type		=> 'ENUM',
				value		=> array('inactive','active','complete','cancel'),	
				form_label  => 'Trạng thái'				
			),
			parent_id		=> array(
				type		=> 'INT',
				form_label  => 'Loại dự án'				
			),
			dateof	=>array(
				type			=> 'FLOAT',
				min				=> 0,
				form_label 		=> 'Số ngày thực hiện',
				default_value	=> NULL	
			)			
		);
		return $data;	
	}
	
	protected function fieldFile(){
		$data = array(
			files => array(
				type 	=> 'FILES',
				path	=> 'files/project/'
			)
		);
		return $data;	
	}
	
	public function initAction(){
		if(!$this->hasRole('task')){
			$this->setContent(error('Bạn không được phép truy cập phân hệ này'));	
			$this->stop();
		}		
		$this->set('task_groups',$this->Model->fetchAll("SELECT * FROM `tasks_types` ORDER BY `title`"));		
		$this->set('project_groups',$this->Model->fetchAll("SELECT * FROM `projects_types` ORDER BY `title`"));		
	}
		
	public function indexAction(){
		$user_id = get_user_id();
		$vars = array();
		
		$order_by = "ORDER BY `a`.`code`";
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('code','title','rate','status','date_start','date_end','date_end_forecast');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$wheres = array();
		
		$wheres[] = "( `c`.`project_id` IS NOT NULL OR `a`.`created_by_id` ='$user_id' )";
		$wheres[] = "`a`.`is_draft`='no'";
		$wheres[] = "( `a`.`created_by_id`='$user_id'	 OR `c`.`user_id`='$user_id' )";
		
		$where = implode(" AND ",$wheres);		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`
			FROM  `projects` as `a`
			LEFT JOIN `projects_users` as `c`
				ON `a`.`ID`=`c`.`project_id` 
					AND `c`.`user_id`='$user_id'
			WHERE $where");		
			
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				IF(`b`.`project_id`,'yes','no') as `is_read` 			
			FROM  `projects` as `a`
			LEFT JOIN `projects_reads` as `b`
				ON `b`.`project_id`=`a`.`ID` AND `b`.`user_id`='$user_id'				
			LEFT JOIN `projects_users` as `c`
				ON `a`.`ID`=`c`.`project_id` 
					AND `c`.`user_id`='$user_id'
			WHERE $where $order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Project?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));
	}

	
	public function archiveAction(){
		$user_id = get_user_id();
		$vars = array();
		
		$order_by = "ORDER BY `a`.`code`";
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('code','title','rate','status','date_start','date_end','date_end_forecast');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$wheres = array();
		$wheres[] = "`a`.`status`='complete'";	
		$wheres[] = "( `c`.`project_id` IS NOT NULL OR `a`.`created_by_id` ='$user_id' )";
		$wheres[] = "`a`.`is_draft`='no'";
		$wheres[] = "( `a`.`created_by_id`='$user_id'	 OR `c`.`user_id`='$user_id' )";
		
		$where = implode(" AND ",$wheres);		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`
			FROM  `projects` as `a`
			LEFT JOIN `projects_users` as `c`
				ON `a`.`ID`=`c`.`project_id` 
					AND `c`.`user_id`='$user_id'
			WHERE $where");		
			
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				IF(`b`.`project_id`,'yes','no') as `is_read` 			
			FROM  `projects` as `a`
			LEFT JOIN `projects_reads` as `b`
				ON `b`.`project_id`=`a`.`ID` AND `b`.`user_id`='$user_id'				
			LEFT JOIN `projects_users` as `c`
				ON `a`.`ID`=`c`.`project_id` 
					AND `c`.`user_id`='$user_id'
			WHERE $where $order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Project?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));
	}		
	
	public function groupAction(){
		$user_id = get_user_id();
		$parent_id = getInt('parent_id',0);
		
		$cat = $this->Model->fetchRow("SELECT * FROM `projects_types` WHERE `ID`='$parent_id'");
		if( !$cat ){
			return $this->setJSON(array(
				content	=> error("Thư mục dự án không tồn tại hoặc đã bị xóa.")
			));
		}
		
		$this->set('cat',$cat);
		
		$vars = array(
			parent_id	=> $parent_id
		);
		
		$order_by = "ORDER BY `a`.`ID` DESC";
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
				
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('code','title','rate','status','date_start','date_end','date_end_forecast');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$wheres = array();
		$wheres[]="`a`.`parent_id` ='$parent_id'";			
		$wheres[]="`a`.`status`<>'complete'";			
		$wheres[] = "( `c`.`project_id` IS NOT NULL OR `a`.`created_by_id` ='$user_id' )";
		$wheres[] = "`a`.`is_draft`='no'";
		$wheres[] = "( `a`.`created_by_id`='$user_id'	 OR `c`.`user_id`='$user_id' )";
		
		$where = implode(" AND ",$wheres);		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`
			FROM  `projects` as `a`
			LEFT JOIN `projects_users` as `c`
				ON `a`.`ID`=`c`.`project_id` 
					AND `c`.`user_id`='$user_id'
			WHERE $where");		
			
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				IF(`b`.`project_id`,'yes','no') as `is_read` 			
			FROM  `projects` as `a`
			LEFT JOIN `projects_reads` as `b`
				ON `b`.`project_id`=`a`.`ID` AND `b`.`user_id`='$user_id'				
			LEFT JOIN `projects_users` as `c`
				ON `a`.`ID`=`c`.`project_id` 
					AND `c`.`user_id`='$user_id'
			WHERE $where $order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Project?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));
	}
	
	public function supervisorAction(){
		$user_id = get_user_id();
		$vars = array();
		$where = array();
		$order_by = "ORDER BY `a`.`ID` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('code','title','rate','status','date_start','date_end','date_end_forecast');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`
			FROM  `projects` as `a`
			LEFT JOIN `projects_users` as `c`
				ON `a`.`ID`=`c`.`project_id` 
					AND `c`.`user_id`='$user_id'
			WHERE
				`c`.`project_id` IS NOT NULL
				AND `a`.`is_draft`='no'
				AND `a`.`status`<>'complete'
				AND `c`.`user_id`='$user_id'
				AND `c`.`is_supervisor`='yes'");
				
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				IF(`b`.`project_id`,'yes','no') as `is_read` 			
			FROM  `projects` as `a`
			LEFT JOIN `projects_reads` as `b`
				ON `b`.`project_id`=`a`.`ID` AND `b`.`user_id`='$user_id'				
			LEFT JOIN `projects_users` as `c`
				ON `a`.`ID`=`c`.`project_id` 
					AND `c`.`user_id`='$user_id'
			WHERE
				`c`.`project_id` IS NOT NULL
				AND `a`.`is_draft`='no'
				AND `a`.`status`<>'complete'
				AND `c`.`user_id`='$user_id'
				AND `c`.`is_supervisor`='yes'					
			$order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Project?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));
	}

	public function guestAction(){
		$user_id = get_user_id();
		$vars = array();
		$where = array();
		$order_by = "ORDER BY `a`.`ID` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = 'LIMIT '.($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('code','title','rate','status','date_start','date_end','date_end_forecast');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`
			FROM  `projects` as `a`
			LEFT JOIN `projects_users` as `c`
				ON `a`.`ID`=`c`.`project_id` 
					AND `c`.`user_id`='$user_id'
			WHERE
				`c`.`project_id` IS NOT NULL
				AND `a`.`is_draft`='no'
				AND `a`.`status`<>'complete'
				AND `c`.`user_id`='$user_id'
				AND `c`.`is_guest`='yes'");
				
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				IF(`b`.`project_id`,'yes','no') as `is_read` 			
			FROM  `projects` as `a`
			LEFT JOIN `projects_reads` as `b`
				ON `b`.`project_id`=`a`.`ID` AND `b`.`user_id`='$user_id'				
			LEFT JOIN `projects_users` as `c`
				ON `a`.`ID`=`c`.`project_id` 
					AND `c`.`user_id`='$user_id'
			WHERE
				`c`.`project_id` IS NOT NULL
				AND `a`.`is_draft`='no'
				AND `a`.`status`<>'complete'
				AND `c`.`user_id`='$user_id'
				AND `c`.`is_guest`='yes'					
			$order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Project?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));
	}	
	
	/* Du an da tao*/
	public function createAction(){
		$user_id = get_user_id();
		$vars = array();
		$where = array();
		$order_by = "ORDER BY `a`.`ID` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p']) ){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('code','title','rate','status','date_start','date_end','date_end_forecast');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		
		$total = $this->Model->fetchOne("SELECT COUNT(*) as `total`
			FROM  `projects` as `a`
			WHERE
				`a`.`is_draft`='no'
				AND `a`.`created_by_id`='$user_id'");
				
		$posts = $this->Model->fetchAll("SELECT `a`.*,
				IF(`b`.`project_id`,'yes','no') as `is_read` 			
			FROM  `projects` as `a`
			LEFT JOIN `projects_reads` as `b`
				ON `b`.`project_id`=`a`.`ID` AND `b`.`user_id`='$user_id'

			WHERE
				`a`.`is_draft`='no'
				AND `a`.`created_by_id`='$user_id'	
			$order_by $limit");
				
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Project?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			posts	=> $posts
		));	
		
	}
	
	public function viewAction(){
		$project_id = getInt('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT `a`.*,
				`b`.`username` as `created_by_name`,
				`b`.`is_deleted` as `created_is_deleted`,
				`c`.`username` as `updated_by_name`,
				`c`.`is_deleted` as `updated_is_deleted`,
				`d`.`title` as `parent_title`
			FROM `projects` as `a` 
			LEFT JOIN `users` as `b` 
				ON `a`.`created_by_id`=`b`.`ID`
			LEFT JOIN `users` as `c` 
				ON `a`.`updated_by_id`=`c`.`ID`
			LEFT JOIN `projects_types` as `d`
				ON `a`.`parent_id`=`d`.`ID`
			WHERE `a`.`ID`='$project_id'");			

		if(!$post){
			return $this->setContent(error("Dự án đã bị xóa hoặc không tồn tại."));
		}
		
		if( $post['created_by_id'] != $user_id ){
			if( !$this->Model->fetchRow("SELECT * FROM `projects_users` WHERE `project_id`='$project_id' AND `user_id`='$user_id'") ){
				return $this->setContent(error("Bạn không có quyền xem dự án này."));			
			}	
		}	
		
		$files	= $this->Model->fetchAll("SELECT * FROM `projects_files` WHERE `project_id`='$project_id'");
		
		$users  = $this
			->Model
			->fetchAll("SELECT `b`.*,`a`.* 
				FROM `users` as `a` 
				LEFT JOIN `projects_users` as `b`
					ON
						`b`.`user_id`=`a`.`ID`
						AND `b`.`project_id`='$project_id'
				WHERE 
					`b`.`project_id`='$project_id'");
		
		if( !$this->Model->fetchRow("SELECT * FROM `projects_reads` WHERE `project_id`='$project_id' AND `user_id`='$user_id'")){
			$this->Model->insert("projects_reads",array(
				project_id	=>	$project_id,
				user_id		=>	$user_id,
				date_read 	=>	mysql_date()
			));	
		}
		
		$tasks = $this->Model->fetchAll("SELECT `a`.*,
				`b`.`username` as `created_by_name`, 
				`b`.`is_deleted` as `created_is_deleted` 
			FROM `tasks` as `a`
			LEFT JOIN `users` as `b`
				ON `b`.`ID`=`a`.`created_by_id`
			WHERE
				`a`.`is_draft` ='no'
				AND `a`.`project_id`='$project_id'");		
	
		$this->set(array(
			users	=> $users,
			files	=> $files,	
			post 	=> $post,
			tasks	=> $tasks
		));	
	}
		
	protected function checkData( $data, $form ){
		if( !is_array( $data ) ){
			return $data;
		}
		
		if( 
			( $data['date_end']  && ( strtotime($data['date_end']) < strtotime($data['date_start']) ) ) 
			|| 
			( $data['date_end_forecast']  && ( strtotime($data['date_end_forecast']) < strtotime($data['date_start']) ) ) 
		){
			return "Thời gian kết thúc và bắt đầu không hợp lệ.";
			$form->freeFile();
		}
		
		return $data;
	}
	
	/* Upload like ajax */
	public function uploadAction(){
		$this->removeLayout();
		$user_id = get_user_id();		
		$project_id = get("ID",0);
		
		$post = $this->Model->fetchRow("SELECT * FROM `projects` WHERE `ID`='$project_id'");
		if( !$post){
			return $this->setJSON(array(
				alert	=> 'Dự án đã bị xóa hoặc không tồn tại.'
			));
		}
		
		if( $post['is_draft'] == 'yes' && !$this->hasRole('add_project')){
			return $this->setJSON(array(
				alert	=> 'Bạn không có quyền tạo dự án.'
			));		
		}	
		
		if( $post['created_by_id'] != get_user_id() ){
			$role = $this
				->Model
				->fetchRow("SELECT * FROM `projects_users` WHERE `project_id`='$project_id' AND `user_id`='$user_id'");
			if( !$role || $role['is_supervisor'] =='no' ){
				return $this->setJSON(array(
					alert	=> 'Bạn không có quyền upload file.'
				));
			}					
		}	
		
		if( isPost() ){
			loadClass("ZData");
			$f = new ZData();

			$f->addField(array(
				file => array(
					type 		=> 'FILE',
					path		=> 'files/project/',
					no_empty	=> true
				)
			));
			
			$data = $f->getData();		
			
			if( is_array( $data ) ){
				$file = $data['file'];
				$this->Model->insert("projects_files",array(
					project_id		=> $project_id,
					name			=> $file[0],
					type			=> $file[1],
					size			=> $file[2],
					filename		=> $file[3]
				));
				
				$file_id = $this->Model->lastId();				
				return $this->setJSON(array(
					content	=> "<div class='x-file-info'><input checked type='checkbox' name='files[]' value='$file_id'/>
						<a href='".ctrUrl($this)."/File?ID=$file_id' target='_blank'>{$file[3]} {$file[2]} KB	</a>
						</div>"
				));
			}else{
				return $this->setJSON(array(
					alert => $data
				));				
			}			
		}
		$this->setJSON(array(
			alert	=> 'Truy cập không được cho phép.'
		));
	}		
	
	public function addAction(){
		$user_id = get_user_id();		
		if( !$this->hasRole('add_project') ){
			return $this->setContent(error("Bạn không được phép tạo dự án."));
		} 	
		
		$post = $this->Model->fetchRow("SELECT * FROM `projects` 
			WHERE `created_by_id`='$user_id' AND `is_draft`='yes' LIMIT 1");
			
		$user = $this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$user_id'");	
		$this->set('user',$user);	
			
		if( $post ){
			$project_id = $post['ID'];

			$files = $this->Model->fetchAll("SELECT * FROM `projects_files` WHERE `project_id`='$project_id'");	
			$users = $this->Model->fetchAll("SELECT * FROM `projects_users` WHERE `project_id`='$project_id'");	
		}else{
			$this->Model->insert("projects",array(
				is_draft		=> 'yes',
				created_by_id	=> $user_id							
			));
			$project_id = $this->Model->lastId();
			$post 	= array(
				ID	=> $project_id
			);
			$files	= array();
			$users	= array();
						
		}
		
		$cats = $this->Model
			->fetchAll("SELECT * 
				FROM `projects_types` ORDER BY `title`");
        
		$auto_code = $this
			->Model
			->fetchOne("SELECT `ID`	FROM `projects` ORDER BY `ID` desc");
		$auto_code = 1+(int)$auto_code;
				
		$this->set(array(
			user	=> $user,
			cats	=> $cats,
			users	=> $users,
			post	=> $post,
			files	=> $files,
            auto_code => (int)$auto_code +1
		));
	
		if(isPost()){		
			$this->removeLayout();			
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->fields() );
			$data = $form->getData();			
			$data = $this->checkData( $data, $form );
			
			if( !is_array( $data )){					
				$this->setJSON(array(
					message => error($data)
				));		
			}
			
			if( $this->Model->fetchRow("SELECT * FROM `projects` WHERE `code`='{$data['code']}'") ){
				return $this->setJSON(array(
					message => error("Mã dự án đã được sử dụng.")
				));
			}
			
			if( !is_array($data) ){
				return $this->setJSON(array(
					message	=> error($data)
				));
			}
			$data['is_draft'] ='no';
			$data['date_created'] = mysql_date();
			$data['created_by_id'] = get_user_id();
			
			$roles = array();				
			$users = (array)$_POST['supervisor'];				
			foreach( $users as $k => $uid ){
				if( !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
					continue;
				}	
				$roles[$uid] = array(
					project_id	=> $project_id,
					user_id		=> $uid,
					is_supervisor	=> 'yes'
				);	
			}			
			
			$users = (array)$_POST['guest'];				
			foreach( $users as $k => $uid ){
				if( !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
					continue;
				}	
				if( isset( $roles[$uid]) ){
					$roles[$uid]['is_guest'] = 'yes';
				}else{
					$roles[$uid] = array(
						project_id	=> $project_id,
						user_id		=> $uid,
						is_guest	=> 'yes'
					);	
				}	
			}	
	
			$files_selected = (array)$_POST['files'];
			$files = $this->Model->fetchAll("SELECT * FROM `projects_files` WHERE `project_id`='$project_id'");
			
			foreach( $files as $f ){
				if( !in_array( $f['ID'], $files_selected ) ){
					$this->Model->delete('projects_files',"`ID`='{$f['ID']}'");
					@unlink("files/project/{$f['name']}");
				}
			}				
			
			//update data
			$this->Model->update('projects',$data,"`ID`='$project_id'");
			if( $data['status'] =='complete' ){
				$data['rate'] = 100;			
				$this->Model->update('tasks',array(
					status	=> 'complete'
				),"`project_id`='$project_id'");					
			}
			
			$this->Model->delete("projects_users","`project_id`='$project_id'");
			foreach( $roles as $role ){
				$this->Model->insert('projects_users',$role);
				$this->Model->insert('notices',array(
					created_by_id	=> $user_id,
					user_id			=> $role['user_id'],
					date			=> mysql_date(),
					title			=> $data['title'],
					url				=> "#Project/Index/View?ID=$project_id",		
					content			=> 'Bạn có mặt trong một dự án.'
				));									
			}
			
			$this->setJSON(array(
				redirect =>	"#Project/Index/View?ID=$project_id"
			));
		}		
	}

	public function editAction(){
		$user_id = get_user_id();
		$project_id = get('ID',0);	
		$post = $this
			->Model
			->fetchRow("SELECT * FROM `projects` WHERE `ID`='$project_id' AND `is_draft`='no' LIMIT 1");
			
		if( !$post ){
			return $this->setContent(error('Dự án không tồn tại hoặc đã bị xóa.'));
		}
		
		//check can modifield
		if( $post['created_by_id'] != $user_id  ){
			return $this->setContent(error('Bạn không có quyền chỉnh sửa dự án này.'));
		}				
				
		$files = $this->Model->fetchAll("SELECT * FROM `projects_files` WHERE `project_id`='$project_id'");	
		$users = $this
			->Model
			->fetchAll("SELECT `b`.*,`a`.* FROM `users` as `a` 
				LEFT JOIN `projects_users` as `b`
				ON 
					`a`.`is_deleted`='no'
					AND `b`.`user_id`=`a`.`ID`
					AND `b`.`project_id`='$project_id'");	
		
		$user = $this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$user_id'");
		$cats = $this->Model->fetchAll("SELECT * FROM `projects_types` ORDER BY `title`");
		
		$this->set(array(
			user	=> $user,
			cats	=> $cats,
			users	=> $users,
			post	=> $post,
			files	=> $files
		));	
	
		if(isPost()){		
			$this->removeLayout();			
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->fields( $post ) );
			$data = $form->getData();			
			$data = $this->checkData( $data, $form );

			if( !is_array($data) ){
				return $this->setJSON(array(
					'message'	=> error($data)
				));
			}						
			
			if( $this->Model->fetchRow("SELECT * FROM `projects` WHERE `code`='{$data['code']}' AND `ID`<>'{$post['ID']}'") ){
				return $this->setJSON(array(
					message => error("Mã dự án đã được sử dụng.")
				));
			}
			
			$roles = array();				
			$users = (array)$_POST['supervisor'];				
			foreach( $users as $k => $uid ){
				if( !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
					continue;
				}	
				$roles[$uid] = array(
					project_id	=> $project_id,
					user_id		=> $uid,
					is_supervisor	=> 'yes'
				);	
			}			
			
			$users = (array)$_POST['guest'];				
			foreach( $users as $k => $uid ){
				if( !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
					continue;
				}	
				if( isset( $roles[$uid]) ){
					$roles[$uid]['is_guest'] = 'yes';
				}else{
					$roles[$uid] = array(
						project_id	=> $project_id,
						user_id		=> $uid,
						is_guest	=> 'yes'
					);	
				}	
			}

			$files_selected = (array)$_POST['files'];
			$files = $this->Model->fetchAll("SELECT * FROM `projects_files` WHERE `project_id`='$project_id'");
			
			foreach( $files as $f ){
				if( !in_array( $f['ID'], $files_selected ) ){
					$this->Model->delete("projects_files","`ID`='{$f['ID']}'");
					@unlink("files/project/{$f['name']}");
				}
			}				
			
			//update data
			$this->Model->update('projects',$data,"`ID`='$project_id'");
			
			if( $data['status'] =='complete' ){
				$data['rate'] = 100;			
				$this->Model->update('tasks',array(
					status	=> 'complete'
				),"`project_id`='$project_id'");					
			}		
			
			$this->Model->delete("projects_users","`project_id`='$project_id'");
			foreach( $roles as $role ){
				$this->Model->insert('projects_users',$role);
				$this->Model->insert('notices',array(
					created_by_id	=> $user_id,
					user_id			=> $role['user_id'],
					url				=> '#Project/Index/View?ID='.$project_id,
					title			=>  $data['title'],
					date			=> new Model_Expr('NOW()'),
					content			=> "Dự án đã được chỉnh sửa."
				));					
			}
			
			$this->setJSON(array(
				redirect =>	"#Project/Index/View?ID=$project_id"
			));
		}		
	}
	
	//update status
	public function statusAction(){
		$user_id = get_user_id();
		$project_id = get('ID',0);	
		$post = $this
			->Model
			->fetchRow("SELECT * 
				FROM `projects` 
				WHERE `ID`='$project_id' 
					AND `is_draft`='no' LIMIT 1");
			
		if( !$post ){
			return $this->setContent(error('Dự án không tồn tại hoặc đã bị xóa.'));
		}
		
		//check can modifield
		if( $post['created_by_id'] != $user_id ){
			if( !$this
				->Model
				->fetchRow("SELECT * 
				FROM `projects_users` 
				WHERE `project_id`='$project_id'
					AND `user_id`='$user_id' AND `is_supervisor`='yes'")){
				return $this->setContent(error('Bạn không có quyền cập nhật.'));
			}
		}				
				
		$this->removeLayout();			
		loadClass("ZData");
		$f = new ZData();
		$f->addFields(array(
			status	=> array(
				type		=> 'ENUM',
				value		=> array('active','inactive','complete','cancel'),
				form_label	=> 'Trạng thái'
			),
			date_updated		=> array(
				type			=> 'NONE',
				default_value	=> mysql_date()
			),		
			updated_by_id	=> array(
				type			=> 'NONE',
				default_value	=> get_user_id()
			)			
		));
		
		$data = $f->getData();	
		if( !is_array( $data ) ){
			return $this->setJSON(array(
				alert	=> $data
			));				
		}
		
		if( $data['status'] =='complete' ){
			$data['rate'] = 100;			
			$this->Model->update('tasks',array(
				status	=> 'complete'
			),"`project_id`='$project_id'");					
		}						
			
		//update data
		$this->Model->update('projects',$data,"`ID`='$project_id'");
		
		$users = $this
			->Model
			->fetchAll("SELECT `b`.*,`a`.* 
				FROM `users` as `a` 
				LEFT JOIN `projects_users` as `b`
				ON 
					`a`.`is_deleted`='no'
					AND `b`.`user_id`=`a`.`ID`
					AND `b`.`project_id`='$project_id'");
					
		foreach( $users as $role ){
			$this->Model->insert('notices',array(
				created_by_id	=> $user_id,
				user_id			=> $role['ID'],
				url				=> "#Project/Index/View?ID=$project_id",
				title			=> $post['title'],
				date			=> mysql_date(),
				content			=> 'Dự án đã chuyển trạng thái.'
			));					
		}
			
		$this->setJSON(array(
			redirect =>	"#Project/Index/View?ID=$project_id"
		));
	}	

	public function deleteAction(){
		$this->removeLayout();
		$project_id = get('ID',0);
		$user_id = get_user_id();
		
		$post = $this->Model->fetchRow("SELECT * FROM `projects` WHERE `ID`='$project_id'");
		
		if( $post && $post['created_by_id'] != $user_id ){
			return $this->setJSON(array(
				alert => 'Chỉ người tạo dự án mới được xóa'			
			));
		}
		
		if( !$post ){
			return $this->setJSON(array(
				alert => 'Dự án đã bị xóa hoặc không tồn tại'			
			));
		}		
		
		$this->Model->delete('projects',"`ID`='$project_id'");

		$files = $this->Model->fetchAll("SELECT * FROM `projects_files` WHERE `project_id`='$project_id'");
		$this->Model->delete("projects_files","`project_id`='$project_id'");
		$this->Model->delete("projects_users","`project_id`='$project_id'");
		$this->Model->delete("projects_reads","`project_id`='$project_id'");
		foreach( $files as $file ){
			@unlink("files/project/{$file['name']}");
		}
			
		//delete all tasks related
		$tasks = $this->Model->fetchAll("SELECT * FROM `tasks` WHERE `project_id`='$project_id' ");
		foreach( $tasks as $task ){
			$task_id = $task['task_id'];
			$files = $this->Model->fetchAll("SELECT * FROM `tasks_files` WHERE `task_id`='$task_id'");
			$this->Model->delete("tasks_files","`task_id`='$task_id'");
			$this->Model->delete("tasks_users","`task_id`='$task_id'");
			$this->Model->delete("tasks_reads","`task_id`='$task_id'");
		
			foreach( $files as $file ){
				@unlink("files/task/{$file['name']}");
			}
			
			$comments = $this->Model->fetchAll("SELECT * FROM `tasks_comments` WHERE `task_id`='$task_id'");			
			$this->Model->delete('tasks_comments',"`task_id`='$task_id'");
			
			foreach( $comments as $comment ){
				$files = $this->Model->fetchAll("SELECT * FROM `tasks_comments_files` WHERE `comment_id`='{$comment['ID']}");
				foreach( $files as $file ){
					@unlink("files/task/{$file['name']}");
				}
			}		
		}
		
		return $this->setJSON(array(
			redirect	=> '#Project'
		));		
	}	
			
	public function fileAction(){
		$this->removeLayout();
		$file_id = get('ID',0);
		$user_id = get_user_id();
		
		$file = $this->Model->fetchRow("SELECT * FROM `projects_files` WHERE `ID`='$file_id' LIMIT 1");

		if( !$file ){
			return $this->setError(404);
		}				
		
		$project_id = $file['project_id'];

		$post = $this->Model->fetchRow("SELECT * FROM `projects` WHERE `ID`='$project_id'");
		
		if( !$post ){
			return $this->setError(404);
		}
		
		if( $post['created_by_id'] != $user_id ){
			if( !$this->Model->fetchRow("SELECT `ID` FROM `projects_users` WHERE `project_id`='$project_id' AND `user_id`='$user_id'") ){
				return $this->setError(404);
			}					
		}
		@header("Content-Disposition: attachment; filename={$file['name']}");
		@readfile("files/project/{$file['name']}");
	}	
		
	public function remindAction(){
		$this->removeLayout();
		$user_id = get_user_id();		
		$id = get("ID",0);
		$i=0;
		$post = $this
			->Model->fetchRow("SELECT * FROM `projects` 
				WHERE `is_draft`='no' AND `ID`='$id' AND `is_draft`='no'");

		if( !$post){
			return $this->setJSON(array(
				alert	=> 'Dự án đã bị xóa hoặc không tồn tại.'
			));
		}
		
		if( !$this->Model->fetchRow("SELECT * 
			FROM `projects_users` 
			WHERE `user_id`='$user_id' 
				AND `project_id`='$id'
				AND `is_supervisor`='yes'	
			") ){		
			return $this->setJSON(array(
				alert	=> 'Chỉ người phụ trách mới được nhắc nhở.'
			));		
		}	
	
		$users = $this
			->Model->fetchAll("SELECT `a`.* 
				FROM `users` as `a` 
				LEFT JOIN `projects_users` as `b` 
					ON `b`.`user_id`=`a`.`ID` AND `b`.`project_id`='$id' 
				WHERE `a`.`is_deleted`='no' AND `b`.`user_id`");
		
		foreach( $users as $user ){
			$i++;
			$this->Model->insert('notices',array(
				created_by_id	=> $user_id,
				user_id	=> $user['ID'],
				url		=> "#Project/Index/View?ID=$id",
				title	=> $post['title'],
				content	=> 'Dự án được nhắc nhở',
				date	=> mysql_date()
			));
		}			
		$this->setJSON(array(
			alert => "Đã gửi thành công $i nhắc nhở"
		));
		
	}	

	public function smsAction(){
		$this->removeLayout();
		$user_id = get_user_id();		
		$post_id = get("ID",0);

		$post = $this
			->Model->fetchRow("SELECT * FROM `projects` 
				WHERE `is_draft`='no' AND `ID`='$post_id' AND `is_draft`='no'");

		if( !$post){
			return $this->setJSON(array(
				alert	=> 'Dự án đã bị xóa hoặc không tồn tại.'
			));
		}
		
		if( !$this->Model->fetchRow("SELECT * 
			FROM `projects_users` 
			WHERE `user_id`='$user_id' 
				AND `project_id`='$post_id'
				AND `is_supervisor`='yes'") ){		
			return $this->setJSON(array(
				alert	=> 'Chỉ người phụ trách mới được nhắc nhở.'
			));		
		}		
	
		if( !isPost() ){
			return false;		
		}				
		
		loadClass('ZData');
		$f = new ZData();
		$f->addFields(array(
			sms_content	=> array(
				type			=> 'CHAR',
				label			=> 'Nội dung',
				max_length		=> 160,
				no_empty		=> true
			)		
		));
		
		$data = $f->getData();		
		
		if( !is_array($data) ){
			$this->setJSON(array(
				alert	=> $data
			));
		}
			
		$users = $this
			->Model->fetchAll("SELECT 
					`a`.`phone`
				FROM `users` as `a` 
				LEFT JOIN `projects_users` as `b` 
					ON `b`.`user_id`=`a`.`ID` AND `b`.`project_id`='$post_id' 
				WHERE `a`.`is_deleted`='no' AND `b`.`user_id`");
				
		foreach( $users as $user ){
			if( is_cellphone($user['phone']) ){
				sendSMS(array(
					content			=>	$data['sms_content'],
					user_id			=>	$user_id,
					address			=>	$user['phone'],
					date_created	=>	new Model_Expr('NOW()'),
					date_send		=>	new Model_Expr('NOW()'),
					mode			=>	'project',
					post_id			=>	$post_id	
				),$this->Model);
			}						
		}			
		
		$this->setJSON(array(
			close	=> true,
			alert 	=> 'Tin SMS của bạn đã được gửi đi',
		));
	}	
}	